<template>
  <div class="w" style="background: #F3F3F3;">
    <van-nav-bar :title="friendInfo.nickName" left-text="返回" left-arrow @click-left="onClickLeft"/>

    <div class="chat-content" id="gundong">
      <!-- recordContent 聊天记录数组-->
      <div v-for="(msg,indexc) in msgList" :key="indexc">
        <!-- 对方 -->
        <div class="word" v-if="!msg.isMe">
          <img :src="friendInfo.headImgUrl">
          <div class="info">
            <p class="time">{{ friendInfo.nickName }} </p>
            <div class="info-content">{{ msg.text }}</div>
          </div>
        </div>
        <!-- 我的 -->
        <div class="word-my" v-else>
          <div class="info">
            <p class="time">{{ meNickName }} </p>
            <div class="info-content">{{ msg.text }}</div>
          </div>
          <img :src="meHeadImg">
        </div>
      </div>
    </div>

    <div class="bottom_msg_send_box">
      <van-field v-model="sendMsgOption.msg" clearable placeholder="请输入你要发送的消息">
        <template #button>
          <van-button size="small" type="primary" @click="sendMsg">发送</van-button>
        </template>
      </van-field>
    </div>
  </div>
</template>

<script>
import api from "@/api/system";
import {Toast} from "vant";
import WebIm from "@/common/initWeb";

export default {
  data() {
    return {
      friendPhone: this.$route.params.id,
      friendInfo: {},
      mePhone: localStorage.getItem("phone"),
      meNickName: localStorage.getItem("nickName"),
      meHeadImg: localStorage.getItem("headImgUrl"),
      msgList: [],
      sendMsgOption: {
        chatType: 'singleChat',// 会话类型，设置为单聊。
        type: 'txt',           // 消息类型。
        to: this.$route.params.id,  // 消息接收方（用户 ID)。
        msg: ''                // 消息内容。
      }
    }
  },
  created() {
    this.getFriendInfo()
    this.initMsgList()
    this.initConn()
    // 清空未读消息
    localStorage.setItem(this.mePhone + "-" + this.friendPhone + "-num", 0);
  },
  methods: {
    // 发送消息
    sendMsg() {
      // 发送消息
      const _this = this
      let msg = this.WebIm.message.create(this.sendMsgOption);
      this.WebIm.conn.send(msg).then((res) => {
        _this.msgList.push({isMe: true, text: _this.sendMsgOption.msg, id: res.serverMsgId})
        // 存储消息到本地
        localStorage.setItem(_this.mePhone + "-" + _this.friendPhone, JSON.stringify(_this.msgList))
        _this.take()
      }).catch((e) => {
        Toast('发送失败，请检查您的网络连接');
      })
    },
    // 获取本地消息
    initMsgList() {
      const data = localStorage.getItem(this.mePhone + "-" + this.friendPhone)
      if (data) {
        this.msgList = JSON.parse(data)
        this.take()
      }
    },
    // 获取朋友的信息
    async getFriendInfo() {
      this.friendInfo = await api.searchUserByPhone(this.friendPhone)
    },
    // 初始化链接监听
    initConn() {
      const _this = this
      this.WebIm.conn.listen({
        onTextMessage: function (message) {
          // 如果是给当前聊天用户发消息，则添加到msgList
          if (_this.friendPhone == message.from) {
            _this.msgList.push({isMe: false, text: message.data, id: message.serverMsgId})
            _this.take()
          }
          //存储消息到本地
          let localMsg = localStorage.getItem(message.to + "-" + message.from);
          let msgList = []
          if (localMsg) {
            msgList = JSON.parse(localMsg)
          }
          msgList.push({isMe: false, text: message.data, id: message.id})
          localStorage.setItem(message.to + "-" + message.from, JSON.stringify(msgList))

        }
      })
    },
    onClickLeft() {
      history.back();
    },
    take() {
      this.$nextTick(() => {
        let msg = document.getElementById('gundong') // 获取对象
        msg.scrollTop = msg.scrollHeight // 滚动高度
      })
    }
  },
  components: {},
}
</script>
<style>
.chat-content::-webkit-scrollbar {
  width: 0;
}

.w::-webkit-scrollbar {
  width: 0;
}
</style>
<style lang="scss" scoped>
.bottom_msg_send_box {
  position: absolute;
  //margin-top: -60px; /*等于footer的高度*/
  width: calc(100vw - 20px);
  background: #ffffff;
  padding: 0 10px;
  height: 45px;
  bottom: 0;
}


.chat-content {
  width: calc(100vw - 40px);;
  padding: 20px;
  height: calc(100vh - 110px);
  overflow: auto;

  .word {
    display: flex;
    margin-bottom: 20px;

    img {
      width: 40px;
      height: 40px;
      border-radius: 50%;
    }

    .info {
      margin-left: 10px;

      .time {
        font-size: 12px;
        color: rgba(51, 51, 51, 0.8);
        margin: 0;
        height: 20px;
        line-height: 20px;
        margin-top: -5px;
      }

      .info-content {
        padding: 10px;
        font-size: 14px;
        background: #fff;
        position: relative;
        margin-top: 8px;
      }

      //小三角形
      .info-content::before {
        position: absolute;
        left: -8px;
        top: 8px;
        content: '';
        border-right: 10px solid #FFF;
        border-top: 8px solid transparent;
        border-bottom: 8px solid transparent;
      }
    }
  }

  .word-my {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 20px;

    img {
      width: 40px;
      height: 40px;
      border-radius: 50%;
    }

    .info {
      width: 90%;
      margin-left: 10px;
      text-align: right;

      .time {
        font-size: 12px;
        color: rgba(51, 51, 51, 0.8);
        margin: 0;
        height: 20px;
        line-height: 20px;
        margin-top: -5px;
        margin-right: 10px;
      }

      .info-content {
        max-width: 70%;
        padding: 10px;
        font-size: 14px;
        float: right;
        margin-right: 10px;
        position: relative;
        margin-top: 8px;
        background: #A3C3F6;
        text-align: left;
      }

      //小三角形
      .info-content::after {
        position: absolute;
        right: -8px;
        top: 8px;
        content: '';
        border-left: 10px solid #A3C3F6;
        border-top: 8px solid transparent;
        border-bottom: 8px solid transparent;
      }
    }
  }
}
</style>
